package com.example.service;

import com.example.DTO.CollectDTO;
import com.example.DTO.ProductDTO;
import com.example.entity.Collect;
import com.example.mapper.CollectMapper;
import com.example.result.Result;
import com.example.vo.CollectVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CollectService {
    @Autowired
    private CollectMapper collectMapper;
    public Result selectbyId(Integer buyerId) {
        List<CollectVO> list=collectMapper.selectbyId(buyerId);
        if(list==null|| list.isEmpty()){
            return Result.success().code(String.valueOf(200)).msg("收藏夹为空");
        }else{
            return Result.success(list);
        }
    }

    public Result addCollectsBatch(CollectDTO collectDTO) {
        List<Integer> productIds = collectDTO.getProductId();
        Integer buyerId = collectDTO.getBuyerId();
        // 1. 查询已存在的商品ID
        List<Integer> existingIds = collectMapper.selectExistingProductIds(buyerId, productIds);
        // 2. 过滤出未收藏的商品ID
        List<Integer> newIds = productIds.stream()
                .filter(id -> !existingIds.contains(id))
                .collect(Collectors.toList());
        if (newIds.isEmpty()) {
            String msg = (productIds.size() == 1)
                    ? "该商品已存在收藏夹中"
                    : "所有商品均已存在收藏夹中";
            return Result.success().code(String.valueOf(200)).msg(msg);
        }
        // 3. 批量插入未收藏的商品
        List<Collect> collectList = newIds.stream()
                .map(productId -> {
                    Collect con = new Collect();
                    con.setBuyerId(buyerId);
                    con.setProductId(productId);
                    con.setCreateTime(LocalDateTime.now());
                    return con;
                })
                .collect(Collectors.toList());

        collectMapper.batchInsertCollects(collectList);
        // 4. 构造响应
        String message = String.format("成功收藏 %d 件商品", newIds.size());
        return Result.success().code(String.valueOf(200)).msg(message);

    }

    public void delCollectsBatch(List<Integer> ids) {
        collectMapper.delCollectsBatch(ids);
    }
}
